<template>
  <div class="out">
    <!-- 查询模块 -->
    <el-input
      placeholder="请输入关键字"
      v-model="selectKey"
      class="input-with-select"
    >
      <el-select v-model="selectType" slot="prepend" placeholder="请选择查询类别">
        <el-option label="车型名称" value="carsName"></el-option>
        <el-option label="车型分类" value="carsType"></el-option>
        <el-option label="容纳人数" value="perNum"></el-option>
        <el-option label="能源类型" value="fuel"></el-option>
      </el-select>
      <el-button slot="append" icon="el-icon-search"  @click="carsSelect(selectType, selectKey)">查询</el-button>
      <el-button slot="append"   @click="reset()">重置</el-button>
    </el-input>



    <!-- 添加模块 -->
    <el-form v-if="false"
      :model="ruleForm"
      ref="ruleForm"
      label-width="100px"
      class="demo-ruleForm"
      :inline="true"
      :max="20"
    >
      <!-- 车型名称 -->
      <el-form-item label="车型名称" width="100px">
        <el-input v-model.lazy="ruleForm.carName"></el-input>
      </el-form-item>
      <!-- 车型分类 -->
      <el-form-item label="车型分类">
        <el-select v-model="ruleForm.carType" placeholder="请选择车型">
          <el-option label="小型车" value="小型车"></el-option>
          <el-option label="中型车" value="中型车"></el-option>
          <el-option label="大型车" value="大型车"></el-option>
        </el-select>
      </el-form-item>
      <!-- 乘坐人数 -->
      乘坐人数：
      <el-input-number
        v-model="ruleForm.accommodation"
        @change="handleChange"
        :min="1"
        :max="50"
        label="乘坐人数"
      ></el-input-number>
      <!-- 燃料类型 -->
      <el-form-item label="能源类型" prop="region">
        <el-select v-model="ruleForm.fuel" placeholder="请选择能源类型">
          <el-option label="柴油" value="柴油"></el-option>
          <el-option label="汽油" value="汽油"></el-option>
        </el-select>
      </el-form-item>
      <!-- 油耗 -->
      油耗：
      <el-input-number
        v-model="ruleForm.fuelConsumption"
        :precision="2"
        :step="0.01"
        :max="100"
      ></el-input-number>
      <el-form-item>

        <el-button
          type="primary"
          @click="addCars(ruleForm)"
          @keyup.enter="addCars(ruleForm)"
          >立即添加</el-button
        >

        <el-button @click="resetForm()">重置</el-button>


      </el-form-item>


    </el-form>
<!--    &lt;!&ndash; 列表模块 &ndash;&gt;      @row-click="handle"-->
    <el-button type="primary" @click="addCarsItem" class="add-btn" plain>新增信息</el-button>
    <el-table
      ref="multipleTable"
      :data="carsItems"
      tooltip-effect="dark"
      style="width: 100%"
      class="eltable"
      @selection-change="handleSelectionChange"
      :default-sort = "{prop: 'accommodation', order: 'ascending'}"

    >
      <el-table-column type="selection" width="55"> </el-table-column>
      <el-table-column label="序号" width="80" type="index">
        <!-- <template slot-scope="scope">{{ scope.row.date }}</template> -->
      </el-table-column>
      <el-table-column prop="carName" label="车型名称" width="120">
      </el-table-column>
      <el-table-column
        prop="carType"
        label="车型分类"
        show-overflow-tooltip
        width="200px"
        :formatter="formatter"
      >

      </el-table-column>
      <el-table-column
        prop="accommodation"
        label="容纳人数"
        sortable
        width="180"

      >
      </el-table-column>
      <el-table-column
        prop="fuel"
        label="燃料种类"
        show-overflow-tooltip
        width="100px"
      ></el-table-column>
      <el-table-column
        prop="fuelConsumption"
        label="油耗(L/百公里)"
        sortable
        width="180"
      >
      </el-table-column>
<!--      <el-table-column label="编辑" width="120">-->
<!--        <el-button type="primary" icon="el-icon-edit" circle @click="editCarsItem(carsItem)"></el-button>-->


<!--        <el-button-->
<!--          type="danger"-->
<!--          icon="el-icon-delete"-->
<!--          circle-->
<!--          @click="delItem()"-->
<!--        ></el-button>-->

<!--      </el-table-column>-->
      <el-table-column label="操作">
        <template scope="scope">
          <el-button type="text" @click="open">点击打开 Message Box</el-button>
          <el-button type="primary" size="small" @click="editCarsItem(scope.row)">编辑</el-button>
          <el-button type="danger" size="small" @click="delItem(scope.row.id)">删除</el-button>
        </template>
      </el-table-column>

      <!-- 编辑 -->
      <el-dialog :title="dTitle" :visible.sync="dialogVisible" :append-to-body="true" >
        <el-form ref="form" :model="newCar" label-width="120px" >
          <el-form-item  label="名称">
            <el-input v-model="newCar.carName" autocomplete="off" ></el-input>
          </el-form-item>
          <el-form-item label="容纳人数">
            <el-input v-model="newCar.accommodation" autocomplete="off"></el-input>
          </el-form-item>
          <el-form-item label="车型分类">
            <el-select v-model="newCar.carType" placeholder="请选择车型">
<!--              <el-option label="请选择车型"  value="0"></el-option>-->
              <el-option label="小型车" v-if="newCar.accommodation>7" :disabled="true" value="1"></el-option>
              <el-option label="小型车" v-else  value="1"></el-option>
              <el-option label="中型车" v-if="newCar.accommodation>20" :disabled="true"  value="2"></el-option>
              <el-option label="中型车" v-else value="2"></el-option>
              <el-option label="大型车"  value="3"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="能源类型">
            <el-input v-model="newCar.fuel" autocomplete="off"></el-input>
          </el-form-item>
          <el-form-item label="油耗(L/百公里)">
            <el-input v-model="newCar.fuelConsumption" autocomplete="off"></el-input>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="dialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="submit()">确 定</el-button>
        </div>
      </el-dialog>

    </el-table>
    <el-button type="danger" size="small" @click="clearCars" v-show="carsItems.length">删除已选中</el-button>
  </div>
</template>

<script>
import { nanoid } from "nanoid";
export default {
  name: "CarsList",
  data() {
    return {
      dialogVisible:false,
      flag:'', //新增:1 修改:0
      newCar:{  //新增/修改 最后要提交的值
         "check": '',
        "isEdit": '',
        "id": '',
        "carName": '',
        "carType": '',
        "accommodation":'',
        "fuel": '',
        "fuelConsumption":'',
    },
      dTitle:'新增',
      selectType: "",
      selectKey: "",
      allData:[],
      // 查询
      input1: "",
      input2: "",
      input3: "",
      select: "",
      // 添加

      ruleForm: {
        check: false,
        isEdit: false,
        id: "",
        carName: "",
        carType: "",
        accommodation: 1,
        fuelConsumption: 1,
        fuel: "",
      },
      // 列表
      carsItems: [
        {
          check: false,
          isEdit: false,
          id: "001",
          carName: "比亚迪-汉",
          carType: "中大型车",
          accommodation: 5,
          fuel: "纯电",
          fuelConsumption: 0.0,
        },
        {
          check: false,
          isEdit: false,
          id: "002",
          carName: "比亚迪-唐",
          carType: "中型车",
          accommodation: 4,
          fuel: "汽油",
          fuelConsumption: 1.0,
        },
        {
          check: false,
          isEdit: false,
          id: "003",
          carName: "唐玄宗",
          carType: "大型车",
          accommodation: 3,
          fuel: "柴油",
          fuelConsumption: 2.0,
        },
        {
          check: false,
          isEdit: false,
          id: "004",
          carName: "汉麒麟宗",
          carType: "小型车",
          accommodation: 2,
          fuel: "汽油柴油",
          fuelConsumption: 3.0,
        },
      ],

    };
  },
  watch: {
   'newCar.accommodation': {
      // immediate: true,
      handler(a, b) {
        console.log(a)
        console.log(b)
        this.newCar.carType=''
      },
    },
  },
  methods: {
    formatter(row, column) {
      if(row.carType == 1){
        return "小型车"
      }else if(row.carType == 2){
        return "中型车"
      }else if(row.carType == 3){
        return "大型车"
      }else{
        return row.carType;
      }
    },
    submit(){
      if (this.flag){
        let date = Date.now();
        this.newCar.id = date
        this.carsItems.push(this.newCar)
        this.dialogVisible = false
        console.log(this.carsItems)
      }else {
        console.log('编辑')
        console.log(this.newCar)
        this.dialogVisible = false
        console.log(this.carsItems)
      }
    },
    // 查询模块
    carsSelect(selectType, selectKey) {
      console.log(selectType,selectKey)
      if (selectType == "carsName") {
        console.log('查询类型为车辆名称！')
        // 如果查询条件是carsName，判断selectKey是否为空
        if (!selectKey.trim()) {
          alert("请输入车辆名称！");
        }
        // carsName不为空，进行查询
        else {
          console.log('查询关键字为'+selectKey)
          this.carsItems=this.allData;
          // this.filcarsItems = this.carsItems.filter((item) => {
          this.carsItems = this.carsItems.filter((item) => {
            return item.carName.indexOf(selectKey) !== -1;
          });
          // console.log(selectType, selectKey);
        }
      }
      // 判断查询条件是不是carsType
      else if (selectType == "carsType") {
        if (!selectKey.trim()) {
          alert("请选择车辆类型！");
        }
        // carsType不为空，进行查询
        else {
          this.carsItems=this.allData;
          // this.filcarsItems = this.carsItems.filter((item) => {
          this.carsItems = this.carsItems.filter((item) => {
            return item.carType.indexOf(selectKey) !== -1;
          });
          // console.log(selectType, selectKey);
        }
      }
      // 判断查询条件是不是perNum
      else if (selectType == "perNum") {
        if (selectKey == "") {
          alert("请输入容纳人数！");
        }
        // perNum不为空，进行查询
        else {
          this.carsItems=this.allData;
          // console.log(typeof(selectKey))
          this.carsItems = this.carsItems.filter((item) => {
            return item.accommodation==selectKey;
          });


        }
        // console.log(selectType, selectKey);
      }
      // 判断查询条件是不是fuel
      else if (selectType == "fuel") {
        if (!selectKey.trim()) {
          alert("请选择能源类型！");
        }
        // fuel不为空，进行查询
        else {
          this.carsItems=this.allData;
          // this.filcarsItems = this.carsItems.filter((item) => {
          this.carsItems = this.carsItems.filter((item) => {
            return item.fuel.indexOf(selectKey) !== -1;
          });
        }
      }
    },
//重置按钮
    reset(){
      //控制重置按钮是否清空查询类型和关键字
      // this.selectType='',
          // this.selectKey='',
          this.carsItems=this.allData;
    },

    //添加功能模块
    addCars() {
      const itemObj = {
        id: nanoid(),
        isEdit: false,
        carName: this.ruleForm.carName,
        carType: this.ruleForm.carType,
        accommodation: this.ruleForm.accommodation,
        fuel: this.ruleForm.fuel,
        fuelConsumption: this.ruleForm.fuelConsumption,
      };

      if (!itemObj.carName.trim()) return alert("车型名称不能为空！");
      else if (!itemObj.carType.trim()) return alert("车型分类不能为空！");
      else if (!itemObj.accommodation) return alert("容纳人数不能为空！");
      else if (!itemObj.fuel.trim()) return alert("能源类型不能为空！");
      else if (!itemObj.fuelConsumption) return alert("油耗不能为空！");
      else {
        this.carsItems.unshift(itemObj);
        this.ruleForm.carName = "";
        this.ruleForm.carType = "";
        this.ruleForm.accommodation = 1;
        this.ruleForm.fuel = "";
        this.ruleForm.fuelConsumption = 1.0;
      }
    },
    //新增
    addCarsItem() {
      this.newCar= {
        "check": '',
            "isEdit": '',
            "id": '',
            "carName": '',
            "carType": '',
            "accommodation":'',
            "fuel": '',
            "fuelConsumption":'',
      }


      this.dialogVisible=true
      this.flag=1
    },
    //编辑按钮
    editCarsItem(row) {
      this.dTitle = '编辑'
      this.newCar=row
      this.dialogVisible=true
      this.flag=0
    },
    open() {
      const h = this.$createElement;
      this.$msgbox({
        title: '消息',
        message: h('p', null, [
          h('span', null, '内容可以是 '),
          h('i', {style: 'color: teal'}, 'VNode')
        ]),
        showCancelButton: true,
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        beforeClose: (action, instance, done) => {
          if (action === 'confirm') {
            instance.confirmButtonLoading = true;
            instance.confirmButtonText = '执行中...';
            setTimeout(() => {
              done();
              setTimeout(() => {
                instance.confirmButtonLoading = false;
              }, 300);
            }, 3000);
          } else {
            done();
          }
        }
      }).then(action => {
        this.$message({
          type: 'info',
          message: 'action: ' + action
        });
      });
    },


    // 保存修改
    saveEdit(carsItem) {
      if (!carsItem.carName.trim()) return alert("车型名称不能为空！");
      else if (!carsItem.carType.trim()) return alert("车型分类不能为空！");
      else if (!carsItem.accommodation) return alert("容纳人数不能为空！");
      else if (!carsItem.fuel.trim()) return alert("能源类型不能为空！");
      else if (!carsItem.fuelConsumption) return alert("油耗不能为空！");
      else {
        carsItem.isEdit = false;
      }
    },
    //删除按钮模块
    // delCarsItem(id) {
    //   // console.log(id);
    //   if (confirm("是否确定删除？")) {
    //     this.carsItems = this.carsItems.filter((caritem) => caritem.id !== id);
    //   }
    // },

    //全选框
    checkedAll(e) {

      this.carsItems.forEach((carsItem) => {
        carsItem.check = e.target.checked;
      });

      // console.log(e.target.checked);
    },

    //清除已选中车辆
    clearCars() {
      if (confirm("是否确定删除？")) {
      this.$refs.multipleTable.selection.forEach((item)=>{


        this.carsItems = this.carsItems.filter((carsItem) => {
          return carsItem.id!==item.id;
        });


      })
      }


    },



    resetForm(formName) {
      this.$refs[formName].resetFields();
    },


    handleChange(value) {
      console.log(value);
    },

    // //列表
    // toggleSelection(rows) {
    //   if (rows) {
    //     rows.forEach((row) => {
    //       this.$refs.multipleTable.toggleRowSelection(row);
    //     });
    //   } else {
    //     this.$refs.multipleTable.clearSelection();
    //   }
    // },
    handleSelectionChange(val) {
      this.multipleSelection = val;
      // console.log(val)
    },
    //删除按钮
    delItem(id) {
      console.log(id)
      // this.carsItems.splice(this.$refs.表格的ref.store.states.selection, 1)
      // this.handle();
      // console.log(id);
      if (confirm("是否确定删除？")) {
        this.carsItems = this.carsItems.filter((caritem) => caritem.id !== id);
      }
    },

  },

  created() {
    this.allData=this.carsItems;
  },
  computed: {
    total() {
      return this.carsItems.length;
    },
    checkedTotal() {
      return this.carsItems.reduce(
          (pre, current) => pre + (current.check ? 1 : 0),
          0
      );
    },

    isAll() {
      return (
          this.checkedTotal === this.carsItems.length && this.carsItems.length > 0
      );
    },
  },
};
</script>

<style>
.input-with-select .el-input-group__prepend {
  background-color: #fff;
}
/* .el-input {
  width: 600px;
} */
/* .el-select {
  width: 130px;
}
.el-form {
  margin-left: 280px;
}
.el-table {
  margin-left: 400px;
} */
</style>

<style scoped>
/*
.el-input,
.el-form,
.el-table {
   align-self: center;
  width: 100px;
} */
.out {
  padding: 10px;
  text-align: center;
}
.mainlist {
  width: 100%;
  margin: 0 auto;
  text-align: center;
}
.el-select {
  width: 130px;
}
.el-input {
  /*width: 600px;*/
  margin-bottom: 10px;
}
.add-btn{
  margin-top: 20px;
  width: 100%;
}

</style>